<template>
  <a-drawer
    title="检查记录信息录入"
    width="840"
    :closable="false"
    @close="onClose"
    :visible="recordAddVisiable"
  >
    <div>
      <a-card
        style="width:100%"
        :tabList="tabListNoTitle"
        :activeTabKey="noTitleKey"
        @tabChange="key => onTabChange(key, 'noTitleKey')"
      >
        <div v-if="noTitleKey === 'recordInfo'" style="heiht:800px;">
          <div>
            <a-form :form="form" layout="inline">
              <a-row>
                <a-form-item label="检查方式" v-bind="formItemLayout">
                  <a-select
                    style="width: 210px"
                    v-decorator="['recordMode',{ initialValue:'1' },
                  {rules: [{ required: true, message: '请选择检查方式' }]}]"
                  >
                    <a-select-option value="1">查资料</a-select-option>
                    <a-select-option value="2">查现场</a-select-option>
                    <a-select-option value="3">现场询问</a-select-option>
                    <a-select-option value="4">现场考核</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="隐患分类" v-bind="formItemLayout">
                  <a-select
                    style="width: 210px"
                    v-decorator="['recordClass',{ initialValue:'1' },
                {rules: [{ required: true, message: '请选择隐患分类' }]}]"
                  >
                    <a-select-option value="1">符合项</a-select-option>
                    <a-select-option value="2">一般隐患</a-select-option>
                    <a-select-option value="3">重大隐患</a-select-option>
                  </a-select>
                </a-form-item>
              </a-row>
              <a-row>
                <a-form-item label="单元" v-bind="formItemLayout">
                  <a-select
                    placeholder="请选择检查单元"
                    optionFilterProp="children"
                    style="width: 220px"
                    :value="unitValue"
                    @change="handleUnitChange"
                  >
                    <a-select-option v-for="u in unitData" :key="u.unitId">{{u.unitName}}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="条目" v-bind="formItemLayout">
                  <a-select
                    placeholder="请选择检查条目"
                    style="width: 220px"
                    :value="entryValue"
                    @change="handleEntryChange"
                  >
                    <a-select-option v-for="e in entryData" :key="e.entryId">{{e.entryNum}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-row>
              <a-form-item label="现场情况" v-bind="{labelCol: {},wrapperCol:{}}">
                <a-textarea
                  :rows="4"
                  style="width: 650px"
                  v-decorator="['recordDesc',
                {rules: [{ max: 225, message: '长度不能超过225个字符'}]}]"
                ></a-textarea>
              </a-form-item>
            </a-form>
          </div>
          <div class="record-bootom-button">
            <a-button @click="tepSave" type="primary" :loading="loading">暂存</a-button>
            <a-button @click="submit" type="primary" :loading="loading">完成</a-button>
            <a-popconfirm title="确定放弃录入？" @confirm="onClose" okText="确定" cancelText="取消">
              <a-button style="margin-right: .8rem">取消</a-button>
            </a-popconfirm>
          </div>
          <div>
            <a-card title="条目提示">
              <a-card-grid style="width:33.3%;textAlign:'center'">{{recordNum}}</a-card-grid>
              <a-card-grid style="width:33.3%;textAlign:'center'">{{recordContent}}</a-card-grid>
              <a-card-grid style="width:33.3%;textAlign:'center'">{{recordBasis}}</a-card-grid>
            </a-card>
          </div>
        </div>
        <div v-else-if="noTitleKey === 'result'">
          <a-table
            :columns="columns"
            :dataSource="data"
            :pagination="false"
            class="components-table-demo-nested"
          ></a-table>
          <a-table
            slot="expandedRowRender"
            :columns="innerColumns"
            :dataSource="innerData"
            :pagination="false"
          ></a-table>
        </div>
      </a-card>
    </div>
  </a-drawer>
</template>
<script>
const formItemLayout = {
  labelCol: {},
  wrapperCol: {}
};
const columns = [
  { title: "检查时间", dataIndex: "time", key: "time" },
  { title: "检查机构", dataIndex: "dept", key: "dpet" },
  { title: "检查形式", dataIndex: "type", key: "type" },
  { title: "检查人员", dataIndex: "person", key: "person" }
];

const innerColumns = [
  { title: "条款", dataIndex: "recordTerms", key: "recordTerms" },
  { title: "检查内容", dataIndex: "recordContent", key: "recordContent" },
  { title: "检查依据", dataIndex: "recordBasis", key: "recordBasis" },
  { title: "检查方式", dataIndex: "recordMode", key: "recordMode" },
  { title: "现场实际情况", dataIndex: "recordDesc", key: "recordDesc" },
  { title: "隐患分类", dataIndex: "recordClass", key: "recordClass" }
];

const i = 0;
export default {
  name: "RecordAdd",
  props: {
    recordAddVisiable: {
      default: false
    },
    report: Object
  },
  data() {
    return {
      data: [],
      columns,
      innerColumns,
      innerData: [],
      formItemLayout,
      form: this.$form.createForm(this),
      noTitleKey: "recordInfo",
      tabListNoTitle: [
        {
          key: "recordInfo",
          tab: "录入信息"
        },
        {
          key: "result",
          tab: "查看结果"
        }
      ],
      unitData: [
        {
          unitId: "",
          unitName: ""
        }
      ],
      entryData: [
        {
          entryId: "",
          entryBasis: "",
          entryContent: "",
          entryNum: ""
        }
      ],
      loading: false,
      recordNum: "",
      recordContent: "",
      recordBasis: "",
      entryVeto: "",
      entryScore: 0,
      entryValue: "",
      unitValue: "",
      recordData: [
        // {
        //   reportId: "",
        //   recordTerms: "",
        //   recordContent: "",
        //   recordBasis: "",
        //   recordMode: "",
        //   recordDesc: "",
        //   recordClass: ""
        // }
      ],
      i: 0,
      score: 0,
      tempScore: 0,
      tempWeight: 0
    };
  },
  methods: {
    handleEntryChange(value) {
      let that = this;
      this.entryValue = value;
      this.entryData.forEach(entry => {
        if (entry.entryId === value) {
          that.recordNum = entry.entryNum;
          that.recordContent = entry.entryContent;
          that.recordBasis = entry.entryBasis;
          that.entryScore = entry.entryScore;
          that.entryVeto = entry.entryVeto;
        }
      });
    },
    handleUnitChange(value) {
      this.unitValue = value;
      this.unitData.forEach(unit => {
        if (unit.unitId === value) {
          this.tempScore = unit.unitScore;
          this.tempWeight = unit.unitWeight;
        }
      });
      this.$get("entry/getEntries/" + value).then(r => {
        this.entryData = r.data.rows;
        if (this.entryData.length) {
          this.entryValue = this.entryData[0].entryId;
          this.recordNum = this.entryData[0].entryNum;
          this.recordContent = this.entryData[0].entryContent;
          this.recordBasis = this.entryData[0].entryBasis;
          this.entryScore = this.entryData[0].entryScore;
          this.entryVeto = this.entryData[0].entryVeto;
        } else {
          this.entryValue = "";
          this.recordNum = "";
          this.recordContent = "";
          this.recordBasis = "";
        }
      });
    },
    submit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.recordData.length) {
            this.$message.warning('至少检查一个项目')
            return;
          }
          this.loading = true;
          this.$post("report", {
            ...this.report
          })
            .then(r => {
              let reportId = r.data.reportId;
              console.log(this.recordData)
              this.recordData.forEach(record => {
                record.reportId = reportId;
                this.$post("record", {
                  ...record
                })
                  .then(() => {})
                  .catch(() => {});
              });
              this.reset();
              this.$emit("success");
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    tepSave() {
      let values = this.form.getFieldsValue([
        "recordDesc",
        "recordMode",
        "recordClass"
      ]);
      let mode = ["", "查资料", "查现场", "现场询问", "现场考核"];
      let rclass = ["", "符合项", "一般隐患", "重大隐患"];
      let flag = false;
      console.log(this.recordData)
      this.recordData.forEach(r => {
        if (r.recordTerms === this.recordNum) {
          flag = true;
        }
      });
      if (flag) {
        this.$message.warning('该条目已经暂存')
        return;
      }
      if (values["recordClass"] == 2) {
        this.score -= this.entryScore * this.tempWeight;
      }
      if (values["recordClass"] == 2 && this.entryVeto == 1) {
        this.score = 0;
      }
      if (values["recordClass"] == 3) {
        this.score = 0;
      }
      this.report.reportScore = this.score;
      this.recordData.push({
        recordTerms: this.recordNum,
        recordContent: this.recordContent,
        recordBasis: this.recordBasis,
        recordMode: values["recordMode"],
        recordDesc: values["recordDesc"],
        recordClass: values["recordClass"],
        reportId: ""
      });
      console.log(this.recordData)
      this.innerData.push({
        key: this.i++,
        recordTerms: this.recordNum,
        recordContent: this.recordContent,
        recordBasis: this.recordBasis,
        recordMode: mode[values["recordMode"]],
        recordDesc: values["recordDesc"],
        recordClass: rclass[values["recordClass"]]
      });
    },
    onTabChange(key, type) {
      this[type] = key;
    },
    reset() {
      this.loading = false;
      this.data = [];
      this.innerData = [];
      this.recordData = [];
      this.score = 0;
      this.form.resetFields();
    },
    onClose() {
      this.reset();
      this.$emit("close");
    }
  },
  watch: {
    recordAddVisiable() {
      if (this.recordAddVisiable) {
        let companyId = this.$db.get("COMPANY");
        this.$get("unit/getUnits/" + companyId.value).then(r => {
          this.unitData = r.data.rows;
          this.unitData.forEach(unit => {
            this.score += unit.unitScore * unit.unitWeight;
          });
          this.unitValue = this.unitData[0].unitId;
          this.handleUnitChange(this.unitData[0].unitId);
          this.data.push({
            key: "1",
            time: this.$dateUtil.formatDate(this.report.createTime),
            dept: this.report.officeName,
            type: this.report.reportTypeName,
            person: this.report.reportPerson
          });
        });
      }
    }
  }
};
</script>
<style scoped>
table {
  border: 1px solid #d9d9d9;
}
td {
  border: 1px solid #d9d9d9;
}
</style>